package com.zenchn.controller;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.common.collect.ImmutableMap;
import com.zenchn.annotation.OperLog;
import com.zenchn.entity.HttpResult;
import com.zenchn.entity.RetrievePwdModifyPwdDO;
import com.zenchn.entity.RetrievePwdSendSmsCaptchaDO;
import com.zenchn.enums.AlidayuSmsEnum;
import com.zenchn.enums.OperLogActionEnum;
import com.zenchn.enums.SessionAttributeEnum;
import com.zenchn.exception.CheckException;
import com.zenchn.external.service.AliSmsApiService;
import com.zenchn.model.TSysAccount;
//import com.zenchn.redis.service.MobilePhoneCaptchaRedisService;
import com.zenchn.service.AccountService;
import com.zenchn.utils.CheckStrength;
import com.zenchn.utils.CommonUtils;
import com.zenchn.utils.PwdHashSaltUtils;
import com.zenchn.utils.RegexKit;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.codec.binary.Base64;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Objects;

/**
 * RetrievePwdController：
 *  平台找回密码功能控制层
 * @author dingxinfa
 * @date 2020-04-20 09:34
 */
@RestController
@RequestMapping(value = "retrievePwd")
@Api(value = "平台找回密码功能相关接口",tags="登录页-找回密码")
public class RetrievePwdController {

    private final String MODULE = "找回密码";


    @Resource
    private AccountService accountService;

    @Resource
    private DefaultKaptcha captchaProducer;


//    @Resource
//    private MobilePhoneCaptchaRedisService captchaRedisService;

    @Resource
    private AliSmsApiService aliSmsApiService;
    /**
     * 图形验证码
     * @param request
     * @param response
     * @throws Exception
     */
    @OperLog(module = MODULE, action = OperLogActionEnum.DEFAULT, detail = "图形验证码")
    @ApiOperation(value = "图形验证码", notes = "图形验证码")
    @GetMapping(value = "/graphicCaptcha")
    public String graphicCaptcha(HttpServletRequest request, HttpServletResponse response) throws Exception {
        byte[] captchaChallengeAsJpeg = null;
        ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();

        //生产验证码字符串并保存到session中
        String createText = captchaProducer.createText();
        request.getSession().setAttribute(SessionAttributeEnum.RETRIEVE_PASSWORD_GRAPHIC_CAPTCHA.getKey(), createText);
        System.out.println("生成图形验证码:"+createText);
        //使用生产的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
        BufferedImage challenge = captchaProducer.createImage(createText);
        ImageIO.write(challenge, "jpg", jpegOutputStream);


        return "data:image/jpeg;base64," + Base64.encodeBase64String(jpegOutputStream.toByteArray());


        //定义response输出类型为image/jpeg类型，使用response输出流输出图片的byte数组
/*        captchaChallengeAsJpeg = jpegOutputStream.toByteArray();

        response.setHeader("Cache-Control", "no-store");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");
        ServletOutputStream responseOutputStream =
                response.getOutputStream();
        responseOutputStream.write(captchaChallengeAsJpeg);
        responseOutputStream.flush();
        responseOutputStream.close();*/
    }


//    /***
//     * 发送手机短信验证码
//     * @param sendSmsCaptchaDO
//     * @param request
//     * @param response
//     * @return
//     * @throws Exception
//     */
//    @OperLog(module = MODULE, action = OperLogActionEnum.CHECK, detail = "发送手机短信验证码")
//    @ApiOperation(value = "发送手机短信验证码", notes = "发送手机短信验证码")
//    @ApiParam(type = "RetrievePwdSendSmsCaptchaDO", name = "sendSmsCaptchaDO", value = "找回密码发送短信验证码提交对象", required = true)
//    @PostMapping(value = "/sendSmsCaptcha")
//    public ResponseEntity<HttpResult> sendSmsCaptcha(
//            @RequestBody @Validated RetrievePwdSendSmsCaptchaDO sendSmsCaptchaDO, BindingResult results,
//            HttpServletRequest request, HttpServletResponse response) throws Exception {
//
//        HttpResult result = new HttpResult(request.getRequestURI());
//
//        if (!RegexKit.getMatcher(sendSmsCaptchaDO.getTel().trim(), RegexKit.REGEX_MOBILE_EXACT).matches()){
//            throw new CheckException("输入手机号码验证不符合规则,请确认！");
//        }
//
//        TSysAccount account=accountService.selectByAccount(sendSmsCaptchaDO.getAccount());
//        if (null==account){
//            throw new CheckException("输入账户名有误，无法找到相关信息！");
//        }
//        if (!account.getTel().equals(sendSmsCaptchaDO.getTel().trim())){
//            throw new CheckException("输入手机号码与账户中手机号码不匹配，无法获取短信验证码！");
//        }
//
//        final String graphicCaptcha = (String) request.getSession().getAttribute(SessionAttributeEnum.RETRIEVE_PASSWORD_GRAPHIC_CAPTCHA.getKey());
//        System.out.println("图形验证码校验:"+graphicCaptcha+"|输入:"+sendSmsCaptchaDO.getGraphicCaptcha());
//        if (graphicCaptcha==null || !graphicCaptcha.equals(sendSmsCaptchaDO.getGraphicCaptcha())){
//            throw new CheckException("图形验证码错误，请确认！");
//        }
//
//        String code=null;
//        String suffixKey="retrievePwd:"+account.getTel();
//        if (captchaRedisService.hasKeyCaptcha(suffixKey)){
//
//            final LocalDateTime sendTime =captchaRedisService.getTime(suffixKey);
//            if (null!=sendTime) {
//                Duration duration = Duration.between(sendTime, LocalDateTime.now());
//                //三分钟内无法再试发送短信验证码
//                int threeMinutes = 3;
//                if (duration.toMinutes() <= threeMinutes) {
//                    throw new CheckException("获取短信验证码过于频繁，请三分钟后再试！");
//                }
//            }
//
//            Integer count=captchaRedisService.getCount(suffixKey);
//            //发送短信不能超过三次
//            int total=3;
//            if (null!=count && count>total){
//                throw new CheckException("获取短信验证码过于频繁，请30分钟后再试！");
//            }
//
//            code=captchaRedisService.getCaptcha(suffixKey);
//            captchaRedisService.refreshCaptcha(suffixKey);
//        }else {
//            code= CommonUtils.randomNumber(6);
//            captchaRedisService.setCaptcha(suffixKey,code);
//        }
//
//        //发送短信验证码
//        if (null!=code) {
//            aliSmsApiService.sendSms(account.getTel(), AlidayuSmsEnum.AUTHENTICATION_TEMPLATE_CODE.getValue(), ImmutableMap.of("code", code, "product", "账户找回密码"));
//        }
//        result.setMessage("OK");
//        result.setStatus(HttpStatus.OK.value());
//        return new ResponseEntity<>(result, HttpStatus.OK);
//    }



//    /***
//     * 找回密码修改密码提交
//     * @param modifyPwdDO
//     * @param request
//     * @param response
//     * @return
//     * @throws Exception
//     */
//    @OperLog(module = MODULE, action = OperLogActionEnum.UPDATE, detail = "找回密码修改密码提交")
//    @ApiOperation(value = "找回密码修改密码提交", notes = "找回密码修改密码提交")
//    @ApiParam(type = "RetrievePwdModifyPwdDO", name = "modifyPwdDO", value = "找回密码修改密码提交对象", required = true)
//    @PutMapping(value = "/retrievePwdModifyPwdSubmit")
//    public ResponseEntity<HttpResult> retrievePwdModifyPwdSubmit(
//            @RequestBody @Validated RetrievePwdModifyPwdDO modifyPwdDO, BindingResult results,
//            HttpServletRequest request, HttpServletResponse response) throws Exception {
//        if (results.hasErrors()){
//            throw new CheckException(Objects.requireNonNull(results.getFieldError()).getDefaultMessage());
//        }
//
//        if (!RegexKit.getMatcher(modifyPwdDO.getTel().trim(), RegexKit.REGEX_MOBILE_EXACT).matches()){
//            throw new CheckException("输入手机号码验证不符合规则,请确认！");
//        }
//
//        TSysAccount account=accountService.selectByAccount(modifyPwdDO.getAccount());
//        if (null==account){
//            throw new CheckException("输入账户名有误，无法找到相关信息！");
//        }
//        if (!account.getTel().equals(modifyPwdDO.getTel().trim())){
//            throw new CheckException("输入手机号码与账户中手机号码不匹配，无法获取短信验证码！");
//        }
//
//        final String graphicCaptcha = (String) request.getSession().getAttribute(SessionAttributeEnum.RETRIEVE_PASSWORD_GRAPHIC_CAPTCHA.getKey());
//        if (!graphicCaptcha.equals(modifyPwdDO.getGraphicCaptcha())){
//            throw new CheckException("图形验证码错误，请确认！");
//        }
//
//        String suffixKey="retrievePwd:"+account.getTel();
//        if (!captchaRedisService.hasKeyCaptcha(suffixKey)) {
//            throw new CheckException("请先发送短信验证码进行本人操作验证！");
//        }
//
//        String captcha=captchaRedisService.getCaptcha(suffixKey);
//        if (!captcha.equals(modifyPwdDO.getSmsCaptcha())){
//            throw new CheckException("手机验证码错误，请确认！");
//        }
//
//        //密码健壮性判断
//        if (CheckStrength.getPasswordLevel(modifyPwdDO.getPassword()).equals(CheckStrength.LEVEL.EASY)){
//            throw new CheckException("新密码过于简单,请重新设置！");
//        }
//
//        HttpResult result = new HttpResult(request.getRequestURI());
//
//
//        account.setPassword(PwdHashSaltUtils.primitiveSha256Hex(account.getAccount(),modifyPwdDO.getPassword()));
//
//        accountService.updateByPrimaryKey(account);
//
//
//        request.getSession().removeAttribute(SessionAttributeEnum.RETRIEVE_PASSWORD_GRAPHIC_CAPTCHA.getKey());
//        captchaRedisService.deleteCaptcha(suffixKey);
//
//        result.setMessage("找回密码成功，请记住新密码！");
//        result.setStatus(HttpStatus.OK.value());
//        return new ResponseEntity<>(result, HttpStatus.OK);
//    }

}
